package com.sms.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sms.dao.IChargeRecordDAO;
import com.sms.po.ChargeRecord;

public class ChargeRecordDAO extends HibernateDaoSupport implements IChargeRecordDAO {
	private static final Log log = LogFactory.getLog(ChargeRecordDAO.class);

	@Override
	public boolean addChargeRecordSerial(ChargeRecord cr) {
		log.debug("add a ChargeRecord instances");
		try{
			this.getHibernateTemplate().save(cr);
			return true;
		}catch(RuntimeException e){
			log.error("add a ChargeRecord failed:",e);
			e.printStackTrace();
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public ChargeRecord findChargeRecordSerialById(final long id) {
		log.debug("find a ChargeRecord instances");
		try{
			return ((List<ChargeRecord>) this.getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query q =  session.createQuery("from ChargeRecord where id=:id ");
					q.setLong("id", id);
					List<ChargeRecord> l = q.list();
					session.close();
					return l;
				}
			})).get(0) ;
		}catch(RuntimeException e){
			log.error("find a ChargeRecord failed:",e);
			e.printStackTrace();
			return null;
		}
	}

	
	@Override
	public boolean removeChargeRecordSerial(ChargeRecord cr) {
		log.debug("delete a ChargeRecord by instances");
		try{
			this.getHibernateTemplate().delete(cr);
			return true;
		}catch(RuntimeException e){
			log.error("delete a ChargeRecord  by instances failed:",e);
			return false;
		}
	}

	@Override
	public boolean removeChargeRecordSerialById(long id) {
		log.debug("delete a ChargeRecord by id ");
		try{
			this.getHibernateTemplate().save(this.findChargeRecordSerialById(id));
			return true;
		}catch(RuntimeException e){
			log.error("add a ChargeRecord by id failed:",e);
			return false;
		}
	}

	@Override
	public boolean updateChargeRecordSerial(ChargeRecord cr) {
		log.debug("update a ChargeRecord instance ");
		try{
			this.getHibernateTemplate().update(cr);
			return true;
		}catch(RuntimeException e){
			log.error("update a ChargeRecord failed:",e);
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ChargeRecord> findChargeRecordSerialByUser(final Map<String,Object> map,final int start,final int limit) {
		log.debug("find a ChargeRecord instances");
		try{
			return (List<ChargeRecord>) this.getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					StringBuffer hql = new StringBuffer("from ChargeRecord where ");
					String usertype = map.get("usertype") != null && !map.get("usertype").toString().trim().equals("") ? map.get("usertype").toString().trim() : null;

					if (usertype.equals("2")){
						if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
							hql.append(" ((userId = :user_id and parentId = :parentId ))");
						else
							hql.append(" (userId = :parentId or parentId = :parentId)");
						
					}else if(usertype.equals("3")){
						hql.append("  (userId = :user_id)");
					}else if(usertype.equals("1")){
						if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
							hql.append("  (userId = :user_id )");
						else
							hql.append(" (1=1)");
					}
					
					if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0 &&
							map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') between :beginDate and :endDate ");
					}else if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') >= :beginDate");
					}else if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') <= :endDate");
					}else{
						hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') = DATE_FORMAT(CURRENT_DATE,'%Y%m%d')");
					}
					
					Query q =  session.createQuery(hql.toString());
					if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
						q.setInteger("beginDate", Integer.valueOf(map.get("beginDate").toString()));
					}
					if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
						q.setInteger("endDate", Integer.valueOf(map.get("endDate").toString()));
					}
					
					if (usertype.equals("2")){
//						hql.append(" and (userId = :user_id or parentId = :parentId)");
						q.setString("parentId", map.get("parentId").toString());
						if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
							q.setString("user_id", map.get("user_id").toString());
						
					}else if(usertype.equals("3")){
						q.setString("user_id", map.get("user_id").toString());
					}else if(usertype.equals("1")){
						if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
							q.setString("user_id", map.get("user_id").toString());
					}
					
					q.setFirstResult(start);
					q.setMaxResults(limit);
					List<ChargeRecord> l = q.list();
					session.close();
					return l;
				}
			}) ;
		}catch(RuntimeException e){
			log.error("add a ChargeRecord failed:",e);
			return null;
		}
	}

	@Override
	public int findChargeRecordSerialByUserCount(final Map<String,Object> map) {
		try{
			StringBuffer hql = new StringBuffer("select count(*) from ChargeRecord where ");
			String usertype = map.get("usertype") != null && !map.get("usertype").toString().trim().equals("") ? map.get("usertype").toString().trim() : null;

			if (usertype.equals("2")){
				if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
					hql.append(" ((userId = :user_id and parentId = :parentId ) )");
				else
					hql.append(" (userId = :parentId or parentId = :parentId)");
//				hql.append(" (userId = :user_id or parentId = :parentId)");
			}else if(usertype.equals("3")){
				hql.append("  (userId = :user_id)");
			}else if(usertype.equals("1")){
				if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
					hql.append("  (userId = :user_id )");
				else
					hql.append(" (1=1)");
			}
			if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0 &&
					map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
				hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') between :beginDate and :endDate ");
			}else if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
				hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') >= :beginDate");
			}else if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
				hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') <= :endDate");
			}else{
				hql.append(" and DATE_FORMAT(create_date,'%Y%m%d') = DATE_FORMAT(CURRENT_DATE,'%Y%m%d')");
			}
			
			Session session = this.getHibernateTemplate().getSessionFactory().openSession();
			Query q = session.createQuery(hql.toString());
//			Query q =  session.createQuery(hql);
			if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals("")){
				q.setString("user_id", map.get("user_id").toString());
			}
			if(map.get("beginDate") != null && map.get("beginDate").toString().trim().length() > 0){
				q.setInteger("beginDate", Integer.valueOf(map.get("beginDate").toString()));
			}
			if(map.get("endDate") != null && map.get("endDate").toString().trim().length() > 0){
				q.setInteger("endDate", Integer.valueOf(map.get("endDate").toString()));
			}
//			if(map.get("create_userid") != null){
//				q.setString("create_userid", map.get("create_userid").toString());
//			}
			if (usertype.equals("2")){
				q.setString("parentId", map.get("parentId").toString());
				if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
					q.setString("user_id", map.get("user_id").toString());
				
			}else if(usertype.equals("3")){
				q.setString("user_id", map.get("user_id").toString());
			}else if(usertype.equals("1")){
				if (map.get("user_id") != null && !map.get("user_id").toString().trim().equals(""))
					q.setString("user_id", map.get("user_id").toString());
			}
			int i = Integer.valueOf(q.list().get(0).toString());
			session.close();
			return i;
		}catch(Exception e){
			e.printStackTrace();
		}
		return 0;
	}

}
